#include "../handler_task.h"
#include "../../conn/proto.h"
#include "../../driver/pipe_line/drop_cup_motor.h"
#include "../../driver/pipe_line/pipe_line_motor.h"
#include "../../service/salve_conn.h"

namespace task {

using namespace conn;
using namespace utils;
using namespace driver;
using namespace service;

static Error on_drop_cup(const Message &msg) {
    uint8_t type;
    Error err = msg.parse(type);
    if (err) {
        goto finish;
    }
    switch (type) {
        case 1: err = dropCupMotor->drop_cup1(); break;
        case 2: err = dropCupMotor->drop_cup2(); break;
        case 3: err = dropCupMotor->drop_cup1_with_check(); break;
        case 4: err = dropCupMotor->drop_cup2_with_check(); break;
        default: err = ec::INVALID; break;
    }
finish:
    return err;
}

static Error on_pipe_line_ctrl(const Message &msg) {
    uint16_t position;
    Error err = msg.parse(position);
    if (err) {
        goto finish;
    }
    err = pipeLineMotor->run(position);
finish:
    return err;
}

void HandlerTask::dispatch_impl(const Message &msg) {

    Error err;

    switch (msg.conn_info.req) {
        case proto::REQ_PIPE_LINE_DROP_CUP:
            err = on_drop_cup(msg);
        break;

        case proto::REQ_PIPE_LINE_MOTOR_CTRL:
            err = on_pipe_line_ctrl(msg);
        break;

        default:
            err = ec::INVALID;
        break;
    }
    salveConn->response(msg, err);
}

}
